<script setup lang="ts">
import * as icons from '@ant-design/icons-vue'
import { isFunction } from '@v-c/utils'
import type { VNodeChild } from 'vue'

const props = withDefaults(defineProps<{
  icon: string | ((...args: any[]) => VNodeChild)
  iconSize?: number
  iconWidth?: number
  iconHeight?: number
  iconOpacity?: number
  iconOffset?: {
    top?: number | string
    bottom?: number | string
    left?: number | string
    right?: number | string
  }
}>(), {
  iconSize: 16,
  iconOpacity: 1,
})

// 判断是否为图片路径
const isImageIcon = computed(() => {
  if (typeof props.icon !== 'string')
    return false
  const iconStr = props.icon
  return iconStr.includes('.jpg') || iconStr.includes('.png') || iconStr.includes('.jpeg') || iconStr.includes('.svg') || iconStr.includes('@/assets/icons/') || iconStr.startsWith('http')
})

const Comp = computed(() => {
  if (isFunction(props.icon)) {
    const node = props.icon()
    if (node)
      return node
  }
  else {
    return (icons as any)[props.icon]
  }
  return undefined
})

// 计算图片样式
const imageStyle = computed(() => {
  // 如果指定了 iconWidth 或 iconHeight，优先使用这些值
  // 否则使用 iconSize 来设置宽高
  const width = props.iconWidth ?? props.iconSize
  const height = props.iconHeight ?? props.iconSize

  const style: Record<string, string> = {
    width: `${width}px`,
    height: `${height}px`,
    opacity: props.iconOpacity?.toString(),
  }

  // 添加偏移量
  if (props.iconOffset) {
    if (props.iconOffset.top !== undefined) {
      style.marginTop = typeof props.iconOffset.top === 'number' ? `${props.iconOffset.top}px` : props.iconOffset.top
    }
    if (props.iconOffset.bottom !== undefined) {
      style.marginBottom = typeof props.iconOffset.bottom === 'number' ? `${props.iconOffset.bottom}px` : props.iconOffset.bottom
    }
    if (props.iconOffset.left !== undefined) {
      style.marginLeft = typeof props.iconOffset.left === 'number' ? `${props.iconOffset.left}px` : props.iconOffset.left
    }
    if (props.iconOffset.right !== undefined) {
      style.marginRight = typeof props.iconOffset.right === 'number' ? `${props.iconOffset.right}px` : props.iconOffset.right
    }
  }

  return style
})
</script>

<template>
  <!-- 如果是图片路径，使用 img 标签渲染 -->
  <img v-if="typeof icon === 'string' && isImageIcon" :src="icon" :style="imageStyle">
  <!-- 否则渲染 Ant Design 图标组件 -->
  <component :is="Comp" v-else-if="icon && !isImageIcon" />
</template>
